<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<head>
<!--
#
# Deepant Anonymous Instant Chat
#
# Copyright (c) 2011, http://deepant.com
#
# This free software is licensed under the GPL License, Version 3, 29 June 2007 (the "License").
# To obtain a copy of the licence, visit : http://www.gnu.org/copyleft/gpl.html
#
# This software is distributed WITHOUT ANY WARRANTY OR CONDITION OF ANY KIND.
# Please see the license for more information.
#
#
-->

<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8" />
<script src="popup.js"></script>
<script  defer>

var   lineNode;
var   chatWindowNode;
var   inputTextNode;
var status = "HANGUP";
var waitingForUserAction = false;  
var token = ""
var isMuted;
var networkErrorCount=0;
var sand = 0;

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

var STORE = {};
STORE.setItem = function (key, value) {
   window.localStorage.setItem(key, value);
}

STORE.getItem = function (key) {
    return window.localStorage.getItem(key);
}

STORE.removeItem = function (key) {
    window.localStorage.removeItem(key);
}


var JSON = JSON || {};
// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function(obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string")
            obj = '"' + obj + '"';
        return String(obj);
    } else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n];
            t = typeof (v);
            if (t == "string")
                v = '"' + v + '"';
            else if (t == "object" && v !== null)
                v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};
// implement JSON.parse de-serialization
JSON.parse = JSON.parse || function() {
    var r = "(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)",
        k = '(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
    k = '(?:"' + k + '*")';
    var s = new RegExp("(?:false|true|null|[\\{\\}\\[\\]]|" + r + "|" + k + ")", "g"),
        t = new RegExp("\\\\(?:([^u])|u(.{4}))", "g"),
        u = {
            '"': '"',
            "/": "/",
            "\\": "\\",
            b: "\u0008",
            f: "\u000c",
            n: "\n",
            r: "\r",
            t: "\t"
        };

    function v(h, j, e) {
        return j ? u[j] : String.fromCharCode(parseInt(e, 16))
    }
    var w = new String(""),
        x = Object.hasOwnProperty;
    return function (h, j) {
        try {
            h = h.match(s);
        }
        catch (e) {
            return h;
        }
        var e, c = h[0],
            l = false;
        if ("{" === c) e = {};
        else if ("[" === c) e = [];
        else {
            e = [];
            l = true
        }
        for (var b, d = [e], m = 1 - l, y = h.length; m < y; ++m) {
            c = h[m];
            var a;
            switch (c.charCodeAt(0)) {
            default:
                a = d[0];
                a[b || a.length] = +c;
                b = void 0;
                break;
            case 34:
                c = c.substring(1, c.length - 1);
                if (c.indexOf("\\") !== -1) c = c.replace(t, v);
                a = d[0];
                if (!b) if (a instanceof Array) b = a.length;
                else {
                    b = c || w;
                    break
                }
                a[b] = c;
                b = void 0;
                break;
            case 91:
                a = d[0];
                d.unshift(a[b || a.length] = []);
                b = void 0;
                break;
            case 93:
                d.shift();
                break;
            case 102:
                a = d[0];
                a[b || a.length] = false;
                b = void 0;
                break;
            case 110:
                a = d[0];
                a[b || a.length] = null;
                b = void 0;
                break;
            case 116:
                a = d[0];
                a[b || a.length] = true;
                b = void 0;
                break;
            case 123:
                a = d[0];
                d.unshift(a[b || a.length] = {});
                b = void 0;
                break;
            case 125:
                d.shift();
                break
            }
        }
        if (l) {
            if (d.length !== 1) throw new Error;
            e = e[0]
        } else if (d.length) throw new Error;
        if (j) {
            var p = function (n, o) {
                var f = n[o];
                if (f && typeof f === "object") {
                    var i = null;
                    for (var g in f) if (x.call(f, g) && f !== n) {
                        var q = p(f, g);
                        if (q !== void 0) f[g] = q;
                        else {
                            i || (i = []);
                            i.push(g)
                        }
                    }
                    if (i) for (g = i.length; --g >= 0;) delete f[i[g]]
                }
                return j.call(n, o, f)
            };

            e = p({
                "": e
            }, "")
        }
        return e
    }
}();

function isIE()
{
    if (navigator.userAgent.indexOf('MSIE') !=-1)
    {
        //alert("IE");
        return true;
    }
    return false;
}

docCookies = {
  getItem: function (sKey) {
    if (!sKey || !this.hasItem(sKey)) { return null; }
    return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
  },
  /**
  * docCookies.setItem(sKey, sValue, vEnd, sPath, sDomain, bSecure)
  *
  * @argument sKey (String): the name of the cookie;
  * @argument sValue (String): the value of the cookie;
  * @optional argument vEnd (Number, String, Date Object or null): the max-age in seconds (e.g., 31536e3 for a year) or the
  *  expires date in GMTString format or in Date Object format; if not specified it will expire at the end of session; 
  * @optional argument sPath (String or null): e.g., "/", "/mydir"; if not specified, defaults to the current path of the current document location;
  * @optional argument sDomain (String or null): e.g., "example.com", ".example.com" (includes all subdomains) or "subdomain.example.com"; if not
  * specified, defaults to the host portion of the current document location;
  * @optional argument bSecure (Boolean or null): cookie will be transmitted only over secure protocol as https;
  * @return undefined;
  **/
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; }
    var sExpires = "";
    if (vEnd) {
      switch (typeof vEnd) {
        case "number": sExpires = "; max-age=" + vEnd; break;
        case "string": sExpires = "; expires=" + vEnd; break;
        case "object": if (vEnd.hasOwnProperty("toGMTString")) { sExpires = "; expires=" + vEnd.toGMTString(); } break;
      }
    }
    document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
  },
  removeItem: function (sKey) {
    if (!sKey || !this.hasItem(sKey)) { return; }
    var oExpDate = new Date();
    oExpDate.setDate(oExpDate.getDate() - 1);
    document.cookie = escape(sKey) + "=; expires=" + oExpDate.toGMTString() + "; path=/";
  },
  hasItem: function (sKey) { return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }
};

function setAttribute(id, name, value)
{
    try
    {
        document.getElementById(id).setAttribute(name,value);
    }
    catch(err)
    {
    }
}

function elementDisabled(id)
{
    if (isIE())
    {
        return document.getElementById(id).disabled;
    }
    else
    {   
        return document.getElementById(id).hasAttribute("disabled");
    }
}

function disableElement(id, shouldDisable)
{
    if (isIE())
    {
        document.getElementById(id).disabled = shouldDisable;
    }
    else
    {
        if (shouldDisable)
        {   
            setAttribute("lineNumber","disabled", "disabled");
        }
        else
        {
            if(document.getElementById("lineNumber").hasAttribute("disabled"))
            {
                document.getElementById("lineNumber").removeAttribute("disabled");
            }
        }
    }    
}

function sendHttpRequest(url, data)
{
    if (waitingForUserAction)
    {
        return "";
    }
    var req = new XMLHttpRequest();
   if (data == "")
    {
       req.open("GET", url, false);
       req.send();
       return req.responseText;
    }
    else
    {
      //post asynchromnous
        document.getElementById("postmsg").value = data;
        setAttribute("postform","action",url);
        document.getElementById("postform").submit();
        return "";
    }
}

function sendHttpRequestAsyn(url, callback)
{
    if (waitingForUserAction)
    {
        return "";
    }
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    
    req.onreadystatechange = function() {
        if (this.readyState == 4)
        {
            if (callback != null)
            {
                if (this.status != 0)
                {   
                    callback(this.responseText);
                }
                else
                {
                    callback("NETWORKERROR");
                }
            }
        }
    };
    req.send();
}

function createLine()
{
    //dochat?action=createline
    var response = sendHttpRequest("dochat?action=createline","");
    if (0 == response.search("!FAIL"))
    {
        showBox(response, "OK", "hideBox()");
        return;
    }
    pos = response.search(":");
    if (pos != -1)
    {
        phone = response.substr(0, pos);
        token = response.substr(pos + 1);
        docCookies.setItem("phone", phone,31536e3, "/chat");
        STORE.setItem("phone", phone);
        docCookies.setItem("token", token,31536e3, "/chat");
        STORE.setItem("token", token);
    }
    if (isNaN(parseInt(phone, 10)))
    {
        phone = "ERROR";
        showBox("Error happen when creating a new line...", "OK", "hideBox()");
    }
    document.getElementById("myPhoneNumber").innerHTML = phone;
}

function connect()
{
    window.setTimeout(function (){doConnect(lineNode.value, document.getElementById("myPhoneNumber").innerHTML);} , 0);
}

function keepAlive()
{
    sendHttpRequest("dochat?action=keepalive&from=" + document.getElementById("myPhoneNumber").innerHTML + "&token=" + token , "");
}

function doConnect(to, from)
{
    //dochat?action=connect&to=XXX&from=XXX&token=XXX
   var response = sendHttpRequest("dochat?action=connect&to=" + to + "&from=" + from + "&token=" + token , "");
   if (-1 != response.search("SUCCESS"))
   {
      STORE.setItem("lastcall", to);
      time = new Date();
      STORE.setItem("lastcalltime", time.toString());
      var nickName = document.getElementById('callee').value;
      if (nickName == null || nickName == "") {
          showInputDialog("Enter your nick name for " + to + ":", function (nick) {document.getElementById('callee').value = nick;saveContact(to, document.getElementById('callee').value);});        
      }
	  return "SUCCESS";
   }
   if (-1 != response.search("BUSY"))
   {
      showBox("LINE BUSY", "OK", "hideBox()");
     return "BUSY";
   }   
   showBox("CONNECTION FAIL", "OK", "hideBox()");
   return "FAIL";
}

function disConnect(toLine)
{
    window.setTimeout(function (){doDisConnect(toLine);}, 0);
}

function doDisConnect(toLine)
{
    if (toLine == null || toLine == "undefined")
    {
        toLine = ""
    }
    //dochat?action=connect&to=&from=XXX&token=XXX
    var response = sendHttpRequest("dochat?action=disconnect&from=" + document.getElementById("myPhoneNumber").innerHTML + "&to=" + toLine+ "&token=" + token, "");
    status = "HANGUP";
}

function promptMsg(newTitle)
{
    if (!isMuted)
    {
        if (null != document.getElementById("playsound").play)
        {
            document.getElementById("playsound").play();
        }
    }
    if (newTitle != null)
    {
        updateTitle(newTitle);
    }
}

function validate(phone, token) {
    try {
        //parse phone into a number
        var len = phone.length;
        if (phone == null ||
                phone == "") {
            return false;
        }

        for (var i = 0; i < len; i++) {
           var code = phone.charCodeAt(i);
           if (code < '0'.charCodeAt(0) || code > '9'.charCodeAt(0)) {
                return false;
           }
        }
        return true;
    }
    catch (e) {
        return false;
    }
    return false;
}

function queryStatusAsyn()
{
      ////dochat?action=connect&from=XXX&token=XXX
    var currentPhone =   document.getElementById("myPhoneNumber").innerHTML;
    var currentToken = token;
    if (false == validate(currentPhone, currentToken)) {
        showBox("Invalid Session! Click OK to get a new phone line!", "OK", "hideBox();createLine();", "Cancel", "hideBox()");
        return false;
    }
    sand++;
    url = "dochat?action=querystatus&from=" + document.getElementById("myPhoneNumber").innerHTML + "&token=" + token + "&sand=" + sand.toString();
    sendHttpRequestAsyn(url, processStatus);
}



function processStatus(currentStatus)
{
    status  = currentStatus;
    disableElement("lineNumber", false);
    
    if (status == "LINEERROR")
    {
        showBox("Session timeout! Please click OK to get a new phone line!", "OK", "hideBox();createLine();", "Cancel", "hideBox()");
        promptMsg("(ERROR)Chat-Deepant");
    }
    else if (status.length >= "NEWMESSAGE".length && status.substr(0, "NEWMESSAGE".length) == "NEWMESSAGE")
    {
        var msg = status;
        status = "CONNECTED";
        promptMsg("(New Message)Chat-Deepant");
        disableElement("lineNumber", true);        
        response = msg.substr("NEWMESSAGE".length);

        processuUpdateChatWindowResponse(response, document.getElementById('callee').value);
        
       // updateChatWindow();
        
    }
    else if(status == "CONNECTED")
    {
        document.getElementById("lineButton").value = "Hangup";
        disableElement("lineNumber", true);
    }
    else if (status == "CONNECTING")
    {
        document.getElementById("lineButton").value = "Calling";
    }
    else if(status == "DISCONNECTED")
    {
        document.getElementById("lineButton").value = "Call";
    }
    else if (-1 != status.search("RINGING:"))
    {

        promptMsg("(New Call)Chat-Deepant");
        incomingCall = status.substr("RINGING:".length);
        
        showAcceptCallBox(incomingCall);
        
    }
    else if (-1 != status.search("BUSY:"))
    {
        promptMsg("(Busy)Chat-Deepant");
        incomingCall = status.substr("BUSY:".length);
        showBusyBox(incomingCall);
        disConnect();
        
    }
    if (-1 != status.search("NETWORKERROR"))
    {
        networkErrorCount = networkErrorCount + 1;
        if (networkErrorCount >= 10)
        {
            networkErrorCount = 0;
            promptMsg("(ERROR)Chat-Deepant");
            showNetworkErrorBox();
        }    
    }
    else
    {
        networkErrorCount = 0;
    }
}

function sendMessage()
{
   if (status != "CONNECTED")
   {
      showBox("not connected", "OK", "hideBox()");
   }
   else
   {
       text = inputTextNode.value;
       text = text.trim();
       processuUpdateChatWindowResponse(text, "Me");
       inputTextNode.value = "";
       doSendMessage(lineNode.value, document.getElementById("myPhoneNumber").innerHTML, text);
   }
}

function doSendMessage(to, from, msg)
{
   //dochat?action=sendmsg&to=xxx&from=xxx&msg=xxx
   sendHttpRequest("dochat?action=sendmsg&to=" + to + "&from=" + from + "&token=" + token +  "&msg=" ,msg);
}

function acceptCall(incomingCall) {
    lineNode.value= incomingCall; 
    var name = lookupNameFromContactNumber(incomingCall);
    if (name == null || name == "") {
       document.getElementById("callee").value = "";
    }
    else {
        document.getElementById("callee").value = name;
    }
    processLineNumberKey(lineNode);
    hideBox();
    connect();
}

function showAcceptCallBox(incomingCall)
{
    showBox("Accept Call from " + incomingCall + "?", "Accept", "acceptCall(incomingCall);", "Deny", "hideBox();disConnect(" + incomingCall + ");");
}

function doInit()
{
    createLine();
    keepAlive();
    setInterval('queryStatusAsyn()', 1000);
}


function showCreateLineBox()
{
    phone = docCookies.getItem("phone");
    if (null == phone) {
        phone = STORE.getItem("phone");
    }
    token = docCookies.getItem("token");
    if (null == token) {
        token = STORE.getItem("token");
    }
    lastcall = STORE.getItem("lastcall");
    lastcalltime = STORE.getItem("lastcalltime");
    if (lastcall != null && lastcalltime != null && lastcall != "" && lastcalltime != "")
    {
        chatWindowNode.value = "You last called " + lastcall +  " at " + lastcalltime + "\n";
        
    }
    if (phone == null || token == null)
    {
       showBox("Apply a new Telephone Line", "OK", "hideBox();window.setTimeout(doInit, 0);");
    }
    else
    {        
        document.getElementById("myPhoneNumber").innerHTML = phone;
        disConnect();
        keepAlive();
        setInterval('queryStatusAsyn()', 1000);        
    }    
}

function showBusyBox(incomingCall)
{
    showBox(incomingCall + " IS BUSY", null, null, "OK", "hideBox();disConnect()");
}
function showNetworkErrorBox()
{
    showBox("NETWORK ERROR", null, null, "OK", "hideBox();");
}

var button1ActionString = "";
var button2ActionString = "";

function showBox(message, button1Value, button1Action, button2Value, button2Action, color, opacity)
{
        if (color == null) {
            color = '#99ff99';
        }
        if (opacity == null) {
            opacity = 0.6;
        }
       document.getElementById("modalText").innerHTML = message;
       if (button1Value != null)
       {
            setAttribute("button1", "value",button1Value);
            button1ActionString = button1Action;
            setAttribute("button1", "type","button");
       }
       else
       {
            setAttribute("button1","type","hidden");
       }
       if (button2Value != null)
       {
            setAttribute("button2", "value",button2Value);
            button2ActionString = button2Action;
            setAttribute("button2", "type","button");
       }
       else
       {
            setAttribute("button2", "value","Cancel");
            button2ActionString = "hideBox()";
            setAttribute("button2","type","hidden");
       }
       renderModalPopup(color, opacity);    
}

function renderModalPopup(color, opacity)
{
   if (waitingForUserAction)
   {
        return;
   }
   waitingForUserAction = true;
   Popup.showModal('modal','container','center center',{'screenColor':color,'screenOpacity':opacity});   
}

function cleanModalPopup()
{
   Popup.hide('modal')
   waitingForUserAction = false;
}

function hideBox()
{
   cleanModalPopup();
}

var isFirstMessage = true;

function processuUpdateChatWindowResponse(response, from) {
        if (null == from || "" == from) {
            from = lineNode.value;
        }
        var value = chatWindowNode.value;
        if (response != null && response != "")
      {
          if (isFirstMessage)
          {
            value = "\n\n" + from + ": " + response;
            isFirstMessage = false;
          }
          else
          {
            value += "\n\n" + from + ": " + response;
          }
          chatWindowNode.value = value;  
          saveHistory();          
          chatWindowNode.scrollTop = chatWindowNode.scrollHeight; 
      }
  
}

function lineButtonClicked(action)
{
   if ("Call" == action)
   {
        connect();
   }
   else if ("Hangup" == action)
   {
        disConnect();
   }
   else if ("Calling" == action)
   {
        disConnect();
   }   
}

function cleanAll()
{
    STORE.setItem("lastcall", "");
    STORE.setItem("lastcalltime", "");
    STORE.setItem("history", "");
    STORE.setItem("contacts", "");
}


function showHistory()
{
    var history = getHistory();
    
    var body = ("<h1>Chat History</h1><input type='button' onClick='window.location.reload();' value='Refresh'></input><BR>");
    body += ("");
    if (history != null && history != "")
    {
        data = unescape(history);
        data = data.replace(/\n/g, "<BR>");
        body +=(data);
    }
    document.body.innerHTML = body;
}

function getHistory()
{
    var history = STORE.getItem("history");
    return history; 
}

time = new Date();
var historyHeader = "\n\n--------Chat on " + time.toString() + "-----------------------";
var pastHistory = getHistory();
var MAX_HISTORY_SIZE = 800000;
var MAX_CONTACTS_SIZE = 30;

if (pastHistory != null && pastHistory != "")
{
    time = new Date();
    pastHistory = unescape(pastHistory);
    if (pastHistory != null && pastHistory.length > MAX_HISTORY_SIZE) {
        pastHistory = pastHistory.substr(0, MAX_HISTORY_SIZE);
    }
}
else
{
    pastHistory = "";
} 

function saveHistory(){
    var current = chatWindowNode.value;
    current = current.replace(/\r\n/g, "\n");
    current = current.replace(/\n\n/g, "\n");
    var data = historyHeader +  current + pastHistory;
    
    if (data != null && data.length > MAX_HISTORY_SIZE * 2) {
        data = data.substr(0, MAX_HISTORY_SIZE * 2);
    }
    STORE.setItem("history", escape(data));
}

function editContact(name, number) {
    showInputDialog("Enter a new name for " + number + " to replace " + name, function (newName) {saveContact(number, newName);;window.location.reload();});        
}

function addContact() {
    showInputDialog("Enter name: ", function (newName) {
            showInputDialog("Enter the number: ", 
                             function (number) {
                                if (true == validate(number, null) ) {
                                    saveContact(number, newName);
                                    window.location.reload();
    }
    else {
                                    alert("Invalid number! " + number);
    }
                            });
        }
    );        
}

function removeContact(number) {
   saveContact(number, ""); 
   contactsString = STORE.getItem("contacts");
   if (contactsString == null || contactsString == "")
   {
    contactsString = "[]";
   }
    var contacts = JSON.parse(contactsString);
    if (contacts.length > 0) {
        contacts.shift();
    }
    STORE.setItem("contacts",JSON.stringify(contacts));
}

function showContacts(){
    var body = ("<h1>Contacts</h1><input type='button' onClick='window.location.reload();' value='Refresh'></input><input type='button' onClick='addContact();' value='Add Contact'></input><BR>");
   contactsString = STORE.getItem("contacts");
   body += "The latest contact appears on the top<BR>================<BR>";
   var str = "";
   if (contactsString != null && contactsString != "")
   {
        var contacts = JSON.parse(contactsString);
        for (var i = 0; i < contacts.length; i++)
        {
            var contact = contacts[i].toString();
            
            var commaIndex = contact.indexOf(":");
            var contactNumber = "";
            var contactName = "";
            if (-1 != commaIndex) {
                contactNumber = contact.substr(0, commaIndex);
                contactName = contact.substr(commaIndex + 1);
            }
            if (contactNumber == "") {
                contactNumber = contact;
            }
            if (contactName == "") {
                contactName = contact;
            }
            contact = "Name: " + contactName + "; Phone: " + contactNumber;
            
            var editContact = "<input type='button' value='Edit' name='Edit' onClick=\"editContact('" + contactName +  "', '" + contactNumber +  "');\" />";
            var removeContact = "<input type='button' value='Remove' name='Remove' onClick=\"removeContact('" + contactNumber +  "');window.location.reload();\" />";
            str += contact + editContact + removeContact + "\n";
        }
        str = str.replace(/\n/g, "<BR>");
        body += (str);
        
        
   }
   document.getElementById("wrapper").setAttribute("style", "display:none");
   document.body.innerHTML = document.body.innerHTML + (body);
}

function lookupNumberFromContactName(name) {
   name  = name.toString();
   var contactsString = STORE.getItem("contacts");
   if (contactsString == null || contactsString == "")
   {
      contactsString = "[]";
   }
    var contacts = JSON.parse(contactsString);
    var foundIndex = -1;
    var contactNumber = "";
    var contactName = "";
    for (var i = 0; i < contacts.length; i++)
    {
        var contact = contacts[i];

        var commaIndex = contact.indexOf(":");

        if (-1 != commaIndex) {
            contactNumber = contact.substr(0, commaIndex);
            contactName = contact.substr(commaIndex + 1);
        }
        if (contactNumber == "") {
            contactNumber = contact;
        }
        if (contactName == "") {
            contactName = contact;
        }

        if (name.toLowerCase() == contactName.toLowerCase()) {
            foundIndex = i;
            break;
        }
    }
    if (-1 != foundIndex) {
        return contactNumber;
    }
    else {
        return "";
    }
}

function lookupNameFromContactNumber(number) {
   number  = number.toString();
   var contactsString = STORE.getItem("contacts");
   if (contactsString == null || contactsString == "")
   {
      contactsString = "[]";
   }
    var contacts = JSON.parse(contactsString);
    var foundIndex = -1;
    var contactNumber = "";
    var contactName = "";
    for (var i = 0; i < contacts.length; i++)
    {
        var contact = contacts[i];

        var commaIndex = contact.indexOf(":");

        if (-1 != commaIndex) {
            contactNumber = contact.substr(0, commaIndex);
            contactName = contact.substr(commaIndex + 1);
        }
        if (contactNumber == "") {
            contactNumber = contact;
        }
        if (contactName == "") {
            contactName = contact;
        }

        if (number == contactNumber) {
            foundIndex = i;
            break;
        }
    }
    if (-1 != foundIndex) {
        return contactName;
    }
    else {
        return "";
    }
}

function saveContact(number, who){
   if (null == who) {
      who = "";
   }
   number = number.toString();
   contactsString = STORE.getItem("contacts");
   if (contactsString == null || contactsString == "")
   {
    contactsString = "[]";
   }
    var contacts = JSON.parse(contactsString);
    var foundIndex = -1;
    for (var i = 0; i < contacts.length; i++)
    {
        var contact = contacts[i];
        var contactNumber = "";
        var commaIndex = contact.indexOf(":");

        if (-1 != commaIndex) {
            contactNumber = contact.substr(0, commaIndex);
        }
        if (contactNumber == "") {
            contactNumber = contact;
        }

        if (number == contactNumber) {
            foundIndex = i;
            break;
        }
    }
    if (-1 == foundIndex)
    {
       contacts.push(number.toString() + ":" + who);
       foundIndex = contacts.length - 1;
    }
    else {
        contacts[foundIndex] = number.toString() + ":" + who;
    }
    if (foundIndex != -1 && foundIndex < contacts.length) {
        //switch to the fist position
        for (var i = foundIndex; i > 0; i--)
        {
            var temp = contacts[i];
            contacts[i] = contacts[i - 1];
            contacts[i - 1] = temp;
        }        
    }
    if (contacts.length > MAX_CONTACTS_SIZE)
    {
        contacts = contacts.slice(0, MAX_CONTACTS_SIZE);
    }
        
   STORE.setItem("contacts",JSON.stringify(contacts));
}

function init()
{
    var url = document.location.href;
    if (-1 != url.search("#history"))
    {
        showHistory();
        return;
    }
    else if(-1 != url.search("#contacts"))
    {
        showContacts();
        return;
    }
    
    lineNode = document.getElementById("lineNumber");
    chatWindowNode = document.getElementById("chatWindow");
    inputTextNode = document.getElementById("inputText");
    lineNode.value = "";
    chatWindowNode.value="";   
    inputTextNode.value="";
    isMuted=strEndsWith(document.getElementById('muteButton').src,'musicoff.jpg'); 
    showCreateLineBox();
}

function processKey(evt)
{
  if (evt.keyCode == 13 && evt.shiftKey)
  {
    //do nothing
  }
  else if (evt.keyCode == 13)
  {
    var value = inputTextNode.value;
    if (value.length > 1)
    {
       value = value.substr(0, value.length - 1);
       inputTextNode.value = value;
    }
    sendMessage();
  }
  
  
}

function updateTitle(title)
{
    document.title=title;
}

function strEndsWith(str, suffix) {
    return str.match(suffix+"$")==suffix;
}

function mute()
{
    isMuted=strEndsWith(document.getElementById('muteButton').src,'musicoff.jpg'); 
    if(isMuted)
    {
        document.getElementById('muteButton').src='musicon.jpg';
    }
    else
    {
        document.getElementById('muteButton').src='musicoff.jpg'
    }
    isMuted=strEndsWith(document.getElementById('muteButton').src,'musicoff.jpg'); 
}

function button1Clicked()
{
    if (button1ActionString != "")
    {
        eval(button1ActionString);
    }
}

function button2Clicked()
{
    if (button2ActionString != "")
    {
        eval(button2ActionString);
    }
}

function processCalleeKey(callee) {
 var value = callee.value;
 if (value == null || value == "") {
    callee.size = 1;
 }
 else
 {
     var length = value.length;
     callee.size = (length > 3) ? (length) : 1;
 }
 if (status != "CONNECTED") {
    if (value != null && value != "") {
        var number = lookupNumberFromContactName(value);
        if (null != number) {
            document.getElementById("lineNumber").value = number;
        }
    }
 }
}

function processLineNumberKey(lineNumber) {
 var number = lineNumber.value;
 
 if (status != "CONNECTED") {
    if (number != null && number != "") {
        var name = lookupNameFromContactNumber(number);
        if (null != name && name != "") {
            document.getElementById("callee").value = name;
        }
    }
 }
}

function showInputDialog (promptMsg, callback) {
   document.getElementById("inputDialogText").innerHTML = promptMsg;
   var inputTag = document.getElementById("inputTag");
   document.getElementById("inputDialogButton").onclick = function (){if (inputTag.value != null && inputTag.value != "") {Popup.hide("inputDialog");callback(inputTag.value);inputTag.value="";}};
   Popup.showModal("inputDialog");
}
</script>




</head>
<body onmouseover="updateTitle('Chat-Deepant')" style="border:0px;margin:0px;padding:0px">
<div style="width:100%;height:100%;background-color: rgb(224, 236, 255);border:0px;margin:0px;padding:0px" id="wrapper">
<div style="width:800px;padding:10px;padding-top:0px" id="container">

<div style="width:100%" >
    <div style="float:left;text-align:left">Anonymous Instant Chat 1.0</div><div style="float:right"><a href="/chat#contacts" target="_blank">Contacts</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="/chat#history"  target="_blank">History</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://clockfly.deepant.com/2011/08/deepant-anonymous-instant-chat-launched.html" target="_blank">Help</a></div>
        <div style="clear:both">
            <div style="float:left">My Phone Number: <span id="myPhoneNumber"></span></div>
            <div style="float:right;position: relative;top: 2px;" onClick="mute()"><img src="musicon.jpg" id="muteButton"/></div><div style="float:right">Dail <input type="text" value="" id='callee' onkeyup="processCalleeKey(this)" size="1" style="color: rgb(0, 0, 0);background-color: #FFFFFF;"/>'s Number <input type="text" style="width:80px;color: rgb(0, 0, 0);background-color: #FFFFFF;" onkeyup="processLineNumberKey(this)" id="lineNumber"></input><input type="button" id="lineButton" value="Call" onClick="lineButtonClicked(this.value)" style="color: rgb(0, 0, 0);"/><input type="hidden" value="Update"  onClick="queryStatusAsyn()"/><input type="button" value="Lock Screen"  onClick='showBox("Screen Locked", "Click to Unlock", "hideBox()", null, null, null, 1);'/><input type="button" value="Clean History"  onClick='showBox("Clean All Histroy and Contacts List?", "OK", "hideBox();cleanAll();", "Cancel", "hideBox()");'/></div>
        </div>
    </div>
    <div style="clear:both">
        <div style="width:100%;height:400px;border:1px solid rgb(0, 0, 0);border-bottom-color:#8C8C8C">
            <textarea style="width:100%;height:399px;border:0px;padding:0px;margin:0px;color: rgb(0, 0, 0);background-color: #FFFFFF;overflow: auto;" id="chatWindow"></textarea>
        </div>
        <div style="height:100px;width:100%;border:1px solid rgb(0, 0, 0);border-top-width: 0px;border-right-width: 0px;"">
            <div style="float:left;width:750px;height:100%;border:0px;padding:0px">
                <textarea style="width:100%;height:99px;border:0px;padding:0px;margin:0px;color: rgb(0, 0, 0);background-color: #FFFFFF;overflow: auto;" id="inputText" onkeyup="processKey(event)"></textarea>
            </div>
            <div style="float:left;height:100%;border:0px;padding:0px" >
                <input type="button"  value="Send"  style="height:100px;width:50px;padding:0px;border-top-width: 0px;" onclick="sendMessage()" />
            </div>
        </div>
    </div>
    <DIV style="text-align:center"><a href="http://deepant.com">Deepant.com</a> | <a href="http://clockfly.deepant.com">Blog</a></DIV>
    <div style="text-align:center"><span>clockfly[at]deepant.com</a></div>
</div>

 
<div id="modal" style="border:3px solid black; background-color:#9999ff; padding:25px; font-size:150%; text-align:center; display:none;">
	<div id="modalText">This is a modal popup!</div>
	<input type="button" value="" onClick="button1Clicked()" id="button1" />
    <input type="button" value="" onClick="button2Clicked()" id="button2" />

</div>



<iframe src="messageposter.html" id="messageposter" name="messageposter" style="visibility:hidden;width:800px;height:1px" ></iframe>

<form action="a.html" method="post" id="postform" target="messageposter" style="visibility:hidden;width:800px;height:1px">
<input type="hidden" id="postmsg" name="msg" />
</form>

<audio id="playsound" style="visibility:hidden;width:800px;height:1px">
  <source src="msg.ogg" type="audio/ogg" />
  <source src="msg.mp3" type="audio/mp3" />
</audio>

</div>
<div id="inputDialog" style="border:3px solid black; background-color:#9999ff; padding:25px; font-size:150%; text-align:center; display:none;">
	<div id="inputDialogText">This is a modal popup!</div>
	<input type="input" value=""  id="inputTag" />
    <input type="button" value="OK"  id='inputDialogButton' />
</div>
</body>
<script  defer>
init();
//showInputDialog("123", gogo);
</script>